package com.lwh.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.lwh.yygh.hosp.repository.ScheduleRepository;
import com.lwh.yygh.hosp.service.ScheduleService;
import com.lwh.yygh.model.hosp.Department;
import com.lwh.yygh.model.hosp.Schedule;
import com.lwh.yygh.vo.hosp.ScheduleQueryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

/**
 * @author lwh
 * @date 2021/6/2 19:39
 */
@Service
public class ScheduleServiceImpl implements ScheduleService {

    @Autowired
    private ScheduleRepository scheduleRepository;


    @Override
    public void save(Map<String, Object> map) {
        String s = JSONObject.toJSONString(map);
        Schedule schedule = JSONObject.parseObject(s,Schedule.class);

        //根据医院编号和课室编号进行查询
        Schedule schedule1Exist = scheduleRepository
                .getScheduleByHoscodeAndHosScheduleId(schedule.getHoscode(),schedule.getHosScheduleId());

        //判断
        if (schedule1Exist!=null) {
            schedule1Exist.setUpdateTime(new Date());
            schedule1Exist.setIsDeleted(0);
            schedule1Exist.setStatus(1);
            scheduleRepository.save(schedule1Exist);
        } else {
            schedule.setUpdateTime(new Date());
            schedule.setCreateTime(new Date());
            schedule.setIsDeleted(0);
            schedule.setStatus(1);
            scheduleRepository.save(schedule);
        }
    }

    @Override
    public Page<Schedule> findPageSchedule(int page, int limit, ScheduleQueryVo queryVo) {
        Schedule schedule = new Schedule();
        BeanUtils.copyProperties(queryVo,schedule);
        schedule.setIsDeleted(0);
        Pageable pageable = PageRequest.of(page-1,limit);
        ExampleMatcher matcher = ExampleMatcher.matching();
        matcher.withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING).withIgnoreCase(true);
        Example<Schedule> example = Example.of(schedule,matcher);

        Page<Schedule> all = scheduleRepository.findAll(example, pageable);
        return all;
    }

    @Override
    public void remove(String hoscode, String hosScheduleId) {
        Schedule schedule = scheduleRepository.getScheduleByHoscodeAndHosScheduleId(hoscode, hosScheduleId);
        if (schedule != null) {
            scheduleRepository.deleteById(schedule.getId());
        }
    }
}


